package com.elepant.thread;

import java.util.Random;

/**
 * Created by Elephant
 * Date：2021/7/1.
 */
public class ThreadContextSwitch {

    private static long[] nums = new long[1_0000_0000];
    private static Random random = new Random();

    static {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = random.nextInt();
        }
    }

    public static void main(String[] args) throws Exception {
        test1();
        test2();
    }

    //1、传统做法 单线程计算
    private static void test1() throws Exception{
        long start = System.currentTimeMillis();
        long total = 0;
        for (int i = 0; i < nums.length; i++) {
            total = total + nums[i];
        }
        long end = System.currentTimeMillis();
        long cost = (end - start);
        System.out.println("test1 result:" + total + " cost:" + cost + " ms ");
    }

    //将采用两个线程同时分开计算，然后把两个结果相加
    static long result1 = 0;
    static long result2 = 0;
    private static void test2() throws Exception {
        long start = System.currentTimeMillis();
        long total = 0;
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < nums.length / 2; i++) {
                result1 = result1 + nums[i];
            }
        });
        thread1.start();

        Thread thread2 = new Thread(()->{
            for (int i = nums.length / 2; i < nums.length; i++) {
                result2 = result2 + nums[i];
            }
        });
        thread2.start();
        thread1.join();
        thread2.join();
        total = result1 + result2;

        long end = System.currentTimeMillis();
        long cost = (end - start);
        System.out.println("test2 result:" + total + " cost:" + cost + " ms ");
    }
}
